package com.laboratory.manage.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laboratory.manage.controller.FileController;
import com.laboratory.manage.dao.PaperDao;
import com.laboratory.manage.entity.PaperEntity;
import com.laboratory.manage.service.PaperService;
import com.laboratory.manage.utils.FileUtils;
import com.laboratory.manage.utils.PageUtils;
import com.laboratory.manage.utils.Query;
import com.laboratory.manage.utils.R;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Ricardo
 * @since 2023-05-12
 */
@Service
public class PaperServiceImpl extends ServiceImpl<PaperDao, PaperEntity> implements PaperService {

    @Autowired
    private PaperDao paperDao;

    @Value("${file.upload-dir}")
    private String uploadPath;

    /*
    *   新版文件上传
    * */
    @Override
    public R upLoadFile(PaperEntity paper) {
        try {
            //String path = ((String) R.ok().get("path"));
            String filePath = FileController.getFilePath();
            paper.setPaperPath(filePath);
            paperDao.insert(paper);
            //return new Result().setCode(200).setMessage("上传成功");
            return R.ok();
        } catch (Exception e) {
            //return new Result().setCode(500).setMessage("上传失败");
            return R.error();
        }
    }

    /**
     * 新版文件修改
     * @param paper
     * @return
     */
    @Override
    public R updateFile(PaperEntity paper) {
        try {
            String filePath = FileController.getFilePath();
            paper.setUpdateTime(Timestamp.valueOf(LocalDateTime.now(ZoneId.of("Asia/Shanghai"))));
//            if (filePath != null){
//                paper.setPaperPath(filePath);
//            }
            paperDao.updateById(paper);
            //return new Result().setCode(200).setMessage("修改成功");
            return R.ok();
        } catch (Exception e) {
            //return new Result().setCode(500).setMessage("修改失败");
            return R.error();
        }
    }

    /**
     * 分页
     */
    @Override
    public IPage<PaperEntity> getPage(int pageNum, int pageSize,PaperEntity paper) {
        LambdaQueryWrapper<PaperEntity> lqw = new LambdaQueryWrapper<PaperEntity>();
        lqw.like(Strings.isNotEmpty(paper.getPaperType()),PaperEntity::getPaperType,paper.getPaperType());
        lqw.like(Strings.isNotEmpty(paper.getSubmitPerson()), PaperEntity::getSubmitPerson, paper.getSubmitPerson());
        IPage<PaperEntity> page = new Page<>(pageNum, pageSize);
        paperDao.selectPage(page,lqw);
        return page;
    }

    //删除
    @Override
    public boolean deleteByIds(Long[] ids) {
        //System.out.println(ids);
        for (int i = 0; i < ids.length; i++) {
            PaperEntity paper = paperDao.selectById(ids[i]);
            //获取存储的路径
            String paperPath = paper.getPaperPath();
            //获取作者路径
            String prePath = FileUtils.extractDirectory(paperPath);
            File file1 = new File(prePath);
            //获取以名字结尾的文件夹路径
            File file = new File(paperPath);
            if (file.exists()){
                file.delete();
                paperDao.deleteById(ids[i]);
            }
            //如果目录下没有论文后，删除该文件
            if (file1 .isDirectory() && file1 .list().length == 0){
                file1.delete();
            }
        }

        return true;
    }


    //分页查询
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PaperEntity> page = this.page(new Query<PaperEntity>().getPage(params),
                new QueryWrapper<PaperEntity>()
        );
        return new PageUtils(page);
    }

}
